<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Db;
use app\admin\model\User;
use think\Config;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
        $this->model = new \app\common\model\Order;
    }  

    /**
     * 购买商城商品
     * @ApiSummary  ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/buy)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=shangcheng_id, type=int, required=true, description="商品id")
     * @ApiParams   (name="num",type=int,required=false,description="数量")
     * @ApiParams   (name="address_id",type=int,required=true,description="收货地址id")
     * @ApiParams   (name="pan_good_id",type=int,required=true,description="抵用卷的pan_good_id")
     */
    public function buy()
    {
        $params = input();
        $params['user_id'] = $this->user_id;
        $params['discount'] = $this->auth->discount;

        $shangcheng_data = Db::name('shangcheng')->field('image,name,price')->where('id',input('shangcheng_id'))->find();
        if(empty($shangcheng_data))$this->error('找不到该商品');
        $params['image'] = $shangcheng_data['image'];
        $params['name'] = $shangcheng_data['name'];
        $params['origin_price'] = $shangcheng_data['price']*$params['num'];
        if(input('pan_good_id')){//使用抵用卷
            $self_diyong = Db::name('cangku')->where('pan_good_id',input('pan_good_id'))->find();
            if(empty($self_diyong))$this->error('抱歉，你没有抵用卷了');

            $reduce_price = Db::name('pan_good')->where('id',input('pan_good_id'))->value('diyong');
            unset($params['pan_good_id']);
            $params['diyong'] = $reduce_price;
            $params['total_price'] = $params['origin_price']*$this->auth->discount-$reduce_price;
            

        }else{
            $params['total_price'] = $params['origin_price']*$this->auth->discount;
        }
        if($params['total_price']<=0){
            $params['total_price'] = 0.01;
        }
        unset($params['pan_good_id']);
        $order_no = $this->model->order_add($params);
        // 发起微信支付
        $this->init_wx_pay_for_wxapp();
     
        $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
    
        $payment = $this->wxapp->payment;
        // halt($payment);
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => '暴富果园',
            'detail'           => '暴富果园',
            'out_trade_no'     => $order_no,
            'openid'           => $third['openid'],
            'total_fee'        => $params['total_price']*100,
            'notify_url'       => Config::get('site.cdnurl').'/api/order/callback_for_wxapp',
        ];

        $order_detail = new WXPAY_ORDER($attributes);
        $result = $payment->prepare($order_detail);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            Db::name('cangku')->where(['user_id'=>$this->user_id,'pan_good_id'=>input('pan_good_id')])->delete();
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return $this->success('订单创建成功,预支付成功',$config);
        }
        return $this->error('微信支付调用失败',$result);
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => true,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

      /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                            'pay_status' => '20',
                            'pay_time' => time(),
                        ]);
                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }
  

}
